<?php
/////////////////////////////////////////////////////////////////////////////
// 
//
// workflow_system
//
// workflow_copyright
// 
/////////////////////////////////////////////////////////////////////////////

/**
 * FILE_NAME : area.class.php   FILE_PATH : \\classes\application\area.class.php
 * ....关于地区管理
 *
 * @copyright workflow_system
 * @author workflow Develop Team 
 * @package
 * @subpackage
 * @version Tue Aug 07 15:39:16 CST 2007
 */

class AreaClass extends FrameWork {

	/**
     * 获得地区的数据库数组资料
     *
     * @return array
     */
	function getArea($condition){
		$conditionstr = $this->_conditionSearch($condition);
		$areaArray = $GLOBALS['db']->GetList($conditionstr, $page, "area");
		return $areaArray;
	}

	/**
	 * 构造检索条件
	 * @author     
	 * @param  
	 * @return 
	 */
	function _conditionSearch($condition){
		$condition_str = '';
		//地区名称
		if ($condition['area_name'] != '') {
			$condition_str .= " and area_name = '". $condition['area_name'] ."'";
		}
		//父ID
		if ($condition['area_parent_id'] != '') {
			$condition_str .= " and area_parent_id = '". $condition['area_parent_id'] ."'";
		}
		//area_id in
		if ($condition['area_id_in'] != '') {
			$condition_str .= " and area_id in (". $condition['area_id_in'] .")";
		}
		//通过path取下级地区
		if ($condition['area_path_like'] != '') {
			$condition_str .= " and area_path_string like '%".$condition['area_path_like']."%'";
		}		
		/*排序*/
		if ($condition['area_sort'] != '') {
			$condition_str .= " order by area_sort asc ";
		}
		if ($condition['order_by'] != ''){
			$condition_str .= " order by ".$condition['order_by'];
		}
		return $condition_str;
	}

	/**
	 * 获得指定ID的资料
	 *
	 * @param int $area_id
	 * @return array $area_row
	 */
	function getAreaRow($area_id){
		if ($area_id > 0){
			return $GLOBALS['db']->GetOneRow($area_id,'area','area_id');
		}
		return false;
	}

	/**
	 * 获得指定中文地区名字的ID
	 *
	 * @param string $area_name
	 * @return int 
	 */
	function getAreaIDRow($area_name){
		if (trim($area_name) != ''){
			return $GLOBALS['db']->GetOneRow(trim($area_name),'area','area_name');
		}
		return false;
	}

	/**
	 * 重新生成全部PATH
	 *
	 * @return Boolean
	 */
	function reCreateAreaPath(){
		$area_row = $GLOBALS['db']->GetAllRow("area","*"," order by area_id asc ");
		foreach ($area_row as $k=>$v){
			$update_array = array();
			if(is_array($v)){
				if (intval($v[area_parent_id])>0){
					$parent_row = $this->getAreaRow(intval($v[area_parent_id]));
					$self_path_string = ','.trim($parent_row['area_path_string'],',').",".$parent_row['area_id'].',';
					$update_array['area_path_string'] = $self_path_string;
				}else{
					$update_array['area_path_string'] = ','.'0'.',';
				}
				$GLOBALS['db']->UpdateRow(intval($v[area_id]),$update_array,"area","area_id");
			}
		}
	}

	/**
	 * 添加地区
	 *
	 * @param array $input
	 * @return bool
	 */
	function addArea($input){
		$valueArray = array();
		$valueArray['area_name'] = str_replace("，",",",trim($input['txtAreaName']));
		$valueArray['area_intro'] = $input['txtAreaIntro'];
		$valueArray['area_parent_id'] = intval($input['txtArea'])?intval($input['txtArea']):'0';
		$valueArray['area_sort'] = $input['txtAreaSort'];
		if ($valueArray['area_parent_id'] > 0){
			$area_array = $this->getAreaRow($valueArray['area_parent_id']);
			$valueArray['area_deeppath'] = $area_array['area_deeppath']+1;
			unset($area_array);
			//
			$id = $valueArray['area_parent_id'];
			$vali_array = array();
			$vali_array[0] = '0';
			for ($i=0;;$i++){
				$area_array = $this->getAreaRow($id);
				$vali_array[] = $area_array['area_id'];
				if ($area_array['area_parent_id'] == '0'){
					break;
				}else {
					$id = $area_array['area_parent_id'];
				}
			}
			//去除重复数据
			$vali_array = array_unique($vali_array);
			//排序
			asort($vali_array);
			//拼成字符串
			$valueArray['area_path_string'] = ','.implode(',',$vali_array).',';
			unset($id,$vali_array);
		}else {
			$valueArray['area_path_string'] = ','.'0'.',';
			$valueArray['area_deeppath'] = 1;
		}
		$result = $GLOBALS['db']->InsertRow($valueArray, 'area', 'area_id');
		return $result;
	}

	/**
	 * 更新地区
	 *
	 * @param array $input
	 * @return bool
	 */
	function updateArea($input){
		//语言包
		$this->getlang('area');
		$valueArray = array();
		$valueArray['area_id'] = intval($input['txtAreaId']);
		$valueArray['area_name'] = trim($input['txtAreaName']);
		$valueArray['area_intro']= $input['txtAreaIntro'];
		$valueArray['area_parent_id'] = $input['txtArea']?$input['txtArea']:'0';
		$valueArray['area_sort'] = intval($input['txtAreaSort']);
		if ($valueArray['area_parent_id'] > 0){
			$area_array = $this->getAreaRow($valueArray['area_parent_id']);
			$valueArray['area_deeppath'] = $area_array['area_deeppath']+1;
			unset($area_array);
			//
			$id = $valueArray['area_parent_id'];
			$vali_array = array();
			$vali_array[0] = '0';
			for ($i=0;;$i++){
				$area_array = $this->getAreaRow($id);
				$vali_array[] = $area_array['area_id'];
				if ($area_array['area_parent_id'] == '0'){
					break;
				}else {
					$id = $area_array['area_parent_id'];
				}
			}
			//去除重复数据
			$vali_array = array_unique($vali_array);
			//排序
			asort($vali_array);
			//拼接后并校验父串中是否已经存在本ID，用来防止选择本或下级类
			if ( in_array($valueArray['area_id'],$vali_array)){
				echo  "{type:0,message:'". $this->_lang['errAreaMergerIsSame'] ."'}";exit;
			}
			//拼成字符串
			$valueArray['area_path_string'] = ','.implode(',',$vali_array).',';
			unset($id,$vali_array);
		}else {
			$valueArray['area_path_string'] = ','.'0'.',';
			$valueArray['area_deeppath'] = 1;
		}
		if ($GLOBALS['db']->UpdateRow($valueArray['area_id'],$valueArray, 'area', 'area_id')){
			$restartarea_result = $this->restArtareaFile();
			if($restartarea_result !== true){
				return false;
			}
			$this->reCreateAreaPath();
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 删除地区
	 *
	 * @param array $input 地区ID
	 * @return Boolean
	 */
	function delArea($input){
//		if (intval($input) > 0){
//			$area_row = $this->getAreaRow(intval($input));
//			$area_parent_id = $area_row['area_parent_id'];
//			$GLOBALS['db']->DeleOneRow(intval($input),'area','area_id');
//			//这里将删除的ID作为父类的类别设置为已删除ID父类为新父类ID的部分。
//			$value_array = array();
//			$value_array['area_parent_id'] = $area_parent_id;
//			$GLOBALS['db']->UpdateRow(intval($input),$value_array, 'area', 'area_parent_id');
//		}else {
//			return false;
//		}
//		$this->reCreateAreaPath();
//		$restartarea_result = $this->restArtareaFile();/*重新生成数组文件*/
//		if($restartarea_result !== true){
//			return false;
//		}
//		return true;
		if (!empty($input)){
			$result = $GLOBALS['db']->DelRow($input,'area','area_id');
			return $result;
		}else {
			return false;
		}
	}

	/**
	 * 重新生成地区
	 */
	function restartAreaFile(){
		require_once("fileoperate.class.php");
		//地区列表
		$condition['order_by'] = "area_deeppath asc,area_parent_id asc,area_sort asc,area_id asc";
		$ar = $this->getArea($condition);
		//定义目标数组
		$d = array();
		//定义索引数组，用于记录节点在目标数组的位置
		$ind = array();
		foreach($ar as $v) {
			$v['child'] = array(); //给每个节点附加一个child项
			if($v['area_parent_id'] == 0) {
				$i = count($d);
				$d[$i] = $v;
				$ind[$v['area_id']] =& $d[$i];
			}else {
				$i = count($ind[$v['area_parent_id']]['child']);
				$ind[$v['area_parent_id']]['child'][$i] = $v;
				$ind[$v['area_id']] =& $ind[$v['area_parent_id']]['child'][$i];
			}
		}
		//生成一维数组，用于后台新增和修改页面的下拉列表
		$result = array();
		$string = $this->getOneLevelArray($result,$d,'0',array(0=>'area_id',1=>'area_parent_id',2=>'area_name',3=>'area_sort'));
		$file_string = $this->getOneLevelString($string);
		$creatfile = "../cache/area.php";
		$make_p_class_single = FileOperate::makeAreaFlie($file_string,$creatfile);
		if ($make_p_class_single !== true) {
			return $make_p_class_single;
		}
		return true;
	}
	
	/**
	 * 生成地区的一维数组
	 * @author     
	 * @param  
	 * @return array
	 */
	function getOneLevelArray(&$result, $node, $depth='0',$Fields){
		if (is_array($node)) {
			foreach ($node as $k => $v){
				$num = count($result);
				$result[$num][0] = $v[$Fields[0]];
				$result[$num][1] = $v[$Fields[1]];
				$result[$num][2] = Common::magic_value($v[$Fields[2]]);
				$result[$num][3] = $v[$Fields[3]];
				$result[$num][4] = $depth;
				if (is_array($v['child'])){
					$line = $depth+1;
					$result = $this->getOneLevelArray($result, $v['child'], $line,$Fields);
				}
				unset($num);
			}
		}
		return $result;
	}
	
	/**
	 * 把一维数组拼成字符串
	 * 
	 * @author     
	 * @param  
	 * @return string
	 */
	function getOneLevelString($param){
		if (is_array($param)) {
			foreach ($param as $k => $v){
				$file_string .="array('".$v[0]."','".$v[1]."','".$v[2]."','".$v[3]."','".$v[4]."',";
				foreach ($param as $k2 => $v2){
					$i = 0;
					if ($v[0] == $v2[1]){
						$i = 1;
						break;
					}
				}
				//haveson 有下级目录的标识，1为有，0为没有
				if ($i == 1){
					$file_string .="1";
				}else {
					$file_string .="0";
				}
				$file_string .="),\n";
			}
		}
		return $file_string;
	}
	
	/**
	 * 更新排序
	 * @author workflow Develop Team
	 * @param  
	 * @return int/bool/object/array
	 */
	function updateAreaSort($SortArray){
		$value_array = array();
		$value_array['area_sort'] = $SortArray['txtAreaSort'];
		$result = $GLOBALS['db']->UpdateRow(intval($SortArray['txtAreaId']),$value_array, 'area', 'area_id');
		if ($result === true){
			return true;
		}
		return false;
	}
	
	/**
	 * 插入全国地区数据
	 * @author workflow Develop Team     
	 * @param  $file_name sql文件名
	 * @return int/bool/object/array/string
	 */
	function insertStandardArea($file_name){
		set_time_limit(0);//设置超时时间为0，表示一直执行。当php在safe mode模式下无效，此时可能会导致导入超时，此时需要分段导入
		$file = @fopen($file_name,'rb');
		$i=0;
		while ($line=@fgets($file)) {
			if ($line[0] != '#'){
				if (substr(trim($line),-1,1) != ';'){
					$sql .= $line;
				}else {
					$sql .= $line;
					//切割数据表名，加入表前缀
					$db_line = explode('`',$sql);
					$sql = $db_line[0].'`'.NC_DBTABLEPRE.$db_line[1].'`'.$db_line[2];
					$GLOBALS['db']->Execute($sql);
					unset($sql);
				}
				$i++;
			}
		}
		@fclose($file);
		return true;
	}
	
	/**
	 * 将旧的父ID更新为新的
	 * @author workflow Develop Team     
	 * @param  old_parent_id 旧的父ID，new_parent_id 新的父ID
	 * @return bool
	 */
	function updateAreaByParentId($param){
		$value_array = array();
		$value_array['area_parent_id'] = $param['new_parent_id'];
		$result = $GLOBALS['db']->UpdateRow(intval($param['old_parent_id']),$value_array, 'area', 'area_parent_id');
		if ($result === true){
			return true;
		}
		return false;
	}
	
	/**
	 * 取地区 所属的各级地区
	 * @author workflow Develop Team     
	 * @param  $area_id 地区ID
	 * @return int/bool/object/array
	 */
	function getAreaPathList($area_id){
		if (intval($area_id) > 0){
			$area_array = $this->getAreaRow(intval($area_id));
			if ($area_array['area_parent_id'] != '0' && !empty($area_array)){
				$condition_area['area_id_in'] = trim($area_array['area_path_string'],',');
				$area_list = $this->getArea($condition_area);
				$area_list[] = $area_array;
			}else {
				$area_list[] = $area_array;
			}
			return $area_list;
		}else {
			return false;
		}
	}
	
	/**
	 * 自定义更新
	 * @author workflow Develop Team     
	 * @param  $input_param
	 * @return bool
	 */
	function updateAreaByCondition($input_param){
		if (is_array($input_param)){
			$value_array = array();
			foreach ($input_param as $k => $v){
				$value_array[$k] = $v;
			}
			$insert_rs = $GLOBALS['db']->UpdateRow($value_array['area_id'],$value_array, 'area', 'area_id');
			return $insert_rs;
		}else {
			return false;
		}
	}
	
	/**
	 * 查找某商品分类没有深度路径的最高父分类
	 *
	 * @param int $parentId
	 * @return bool
	 */
	function updateAreaDeepPath($classID,$level = 0){
		$parent_array = $GLOBALS['db']->GetAllRow("area","area_id,area_parent_id,area_deeppath"," where area_parent_id='" . $classID . "'");
		if (count($parent_array) > 0){
			foreach($parent_array as $k=>$v){
				$value_array = array();
				$value_array['area_deeppath'] = $level+1;
				$result = $GLOBALS['db']->UpdateRow($v['area_id'],$value_array,'area','area_id');
				$this->updateAreaDeepPath($v['area_id'],$level+1);
			}
		}
		return true;
	}
	
	/**
	 * 转移类别下的地区到另一个类别中
	 * @author workflow Develop Team     
	 * @param  $move_array需要转移的ID数组,$to_id转入的类别ID
	 * @return bool
	 */
	function moveAreaClass($move_array,$to_id){
		if (intval($to_id) > 0 && !empty($move_array)){
			foreach ($move_array as $k => $v){
				$condition_str[] = "area_id = '" . $v . "'";
			}
			$condition_str = implode(' or ',$condition_str);
			$value_array = array();
			$value_array['area_parent_id'] = intval($to_id);
			if (substr(trim($condition_str),0,3) == 'and'){
				$condition_str = substr(trim($condition_str),3);
			}
			$result = $GLOBALS['db']->UpdateRows('area',$value_array,$condition_str);
			unset($condition,$condition_str,$value_array);
			return $result;
		}
		return false;
	}
}
?>